package com.yuanyi.controller;

import com.yuanyi.dao.RepairManDao;
import com.yuanyi.entity.BaoXiuMan;
import com.yuanyi.entity.RepairMan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.UUID;

@RestController
public class RepairManController {
    @Autowired
    RepairManDao repairManDao;

    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @GetMapping(value = "/rm_shenhe",produces = "application/json;charset=utf-8")
    @ResponseBody
    public boolean rm_shenhe(@RequestParam("bxm_id") Integer bxm_id,@RequestParam("status") Integer status,
                              @RequestParam(value="rejectMsg", required=false) String rejectMsg){
        try{
            RepairMan repairMan = repairManDao.findRepairManById(bxm_id);
            repairMan.setStatus(status);
            repairMan.setRejectMsg(rejectMsg);
            repairManDao.save(repairMan);
        }catch (Exception ex){
            return false;
        }
        return true;
    }

    @GetMapping("tel_isrepeat")
    public boolean isrepeat(String tel){
        return repairManDao.findRepairManByTel(tel)==null;
    }

    @GetMapping("/find_repairman_byopenid")
    public RepairMan findRepairManByOpenid(String openid){
        return repairManDao.findRepairManByOpenid(openid);
    }

    @PostMapping("repair_man_bind")
    public RepairMan bangding(@RequestBody RepairMan repairMan){
        String yzm = repairMan.getYzm();

        String redisYZM = (String) redisTemplate.opsForValue().get(repairMan.getTel());
        if(!yzm.equals(redisYZM)){
            return null;
        }

        if(repairMan.getOpenid().length()==0){
            repairMan.setOpenid(UUID.randomUUID().toString());
        }

        RepairMan r = null;
        try {
             r = repairManDao.save(repairMan);
        }catch (Exception ex){
            if(ex instanceof DuplicateKeyException){
                return null;
            }
        }

        return r;
    }

    @GetMapping(value = "/find_top_repair_man",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Page<RepairMan> findAll(@RequestParam("p") Integer p,@RequestParam("size") Integer size){
      Sort sort = new Sort(Sort.Direction.ASC,"id");
//
       PageRequest pr =  PageRequest.of(p-1,size,sort);
       // Pageable pageable = new PageRequest(p - 1, size);
        return repairManDao.findAll(pr);
    }
}